"""
 作者： 临渊
 日期： 2025/7/7
 小程序：   爷爷不泡茶
 功能： 获取token和手机号
 变量： yybpc_wxid_data (微信id) 多个账号用换行分割 
        PROXY_API_URL (代理api，返回一条txt文本，内容为代理ip:端口)
 定时： 一天一次
 cron： 10 8 * * *
 更新日志：
 2025/7/7 V1.0 初始化脚本
 2025/7/7 V1.1 使用wex_get模块统一微信授权接口
"""

import requests
import time
import json
import os
# 导入wex_get模块中的wx_code_auth方法
from wex_get import wx_code_auth

# 配置参数
CONFIG = {
    'delay': 1.5,             # 操作间隔秒
    'account_delay': 2,       # 账号间隔秒
    'retry_count': 3,         # 重试次数
    'execution_times': 1      # 每个账号执行次数
}

# API
BASE_URL = "https://webapi.qmai.cn"
BIND_API = f"{BASE_URL}/web/account-center/oauth/bind-mobile"

APPID = "wx3423ef0c7b7f19af"
STORE_ID = "216652"
REFERER = "https://servicewechat.com/wx3423ef0c7b7f19af/72/page-frame.html"

# ===================== 微信小程序code获取 =====================
def get_wxapp_code(wxid, appid):
    """
    获取小程序code（使用wex_get模块）
    Args:
        wxid (str): 微信ID
        appid (str): 小程序的appid
    Returns:
        dict: 请求结果，包含success字段和提取的code
    """
    try:
        code = wx_code_auth(wxid, appid)
        if code:
            return {
                'success': True,
                'extracted_code': code
            }
        else:
            return {
                'success': False,
                'error': '获取code失败'
            }
    except Exception as e:
        return {
            'success': False,
            'error': f'请求异常: {str(e)}'
        }

def get_yybpc_token(wxid):
    """
    获取爷爷不泡茶token和手机号
    Args:
        wxid (str): 微信ID
    Returns:
        dict: {success, token, openid, unionid, purePhoneNumber, ...}
    """
    code_result = get_wxapp_code(wxid, APPID)
    if not code_result.get('success') or not code_result.get('extracted_code'):
        return {'success': False, 'error': f"获取code失败: {code_result.get('error')}", 'wxid': wxid}
    code = code_result['extracted_code']
    # 第一步：用code请求mini-app-login获取token_0
    login_headers = {
        'qm-user-token': '',
        'store-id': STORE_ID,
        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36 MicroMessenger/7.0.20.1781(0x6700143B) NetType/WIFI MiniProgramEnv/Windows WindowsWechat/WMPF WindowsWechat(0x63090c33)XWEB/13639',
        'content-type': 'application/json',
        'qm-from': 'wechat',
        'accept': 'v=1.0',
        'xweb_xhr': '1',
        'qm-from-type': 'catering',
        'sec-fetch-site': 'cross-site',
        'sec-fetch-mode': 'cors',
        'sec-fetch-dest': 'empty',
        'referer': REFERER,
        'accept-encoding': 'gzip, deflate, br',
        'accept-language': 'zh-CN,zh;q=0.9',
        'priority': 'u=1, i'
    }
    login_payload = {
        "code": code,
        "appid": APPID
    }
    try:
        login_resp = requests.post(BASE_URL + "/web/account-center/oauth/mini-app-login", headers=login_headers, json=login_payload, timeout=15)
        login_data = login_resp.json()
        # print(login_data)
        if login_data.get('code') != 0 or not login_data.get('data') or not login_data['data'].get('token'):
            return {'success': False, 'error': f"mini-app-login失败: {login_data.get('message', '未知错误')}", 'wxid': wxid}
        token_0 = login_data['data']['token']
    except Exception as e:
        return {'success': False, 'error': f"mini-app-login异常: {e}", 'wxid': wxid}
    # 第二步：用token_0作为qm-user-token请求bind-mobile
    headers = {
        'qm-user-token': token_0,
        'store-id': STORE_ID,
        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36 MicroMessenger/7.0.20.1781(0x6700143B) NetType/WIFI MiniProgramEnv/Windows WindowsWechat/WMPF WindowsWechat(0x63090c33)XWEB/13639',
        'content-type': 'application/json',
        'qm-from': 'wechat',
        'accept': 'v=1.0',
        'xweb_xhr': '1',
        'qm-from-type': 'catering',
        'sec-fetch-site': 'cross-site',
        'sec-fetch-mode': 'cors',
        'sec-fetch-dest': 'empty',
        'referer': REFERER,
        'accept-encoding': 'gzip, deflate, br',
        'accept-language': 'zh-CN,zh;q=0.9',
        'priority': 'u=1, i'
    }
    payload = {
        "code": code,
        "reg_activity_source": 0,
        "is_update_mobile": 0,
        "channel_code": "",
        "flowScene": 1256,
        "appid": APPID
    }
    try:
        resp = requests.post(BIND_API, headers=headers, json=payload, timeout=15)
        data = resp.json()
        # print(data)
        if data.get('code') == 0 and data.get('data') and 'loginToken' in data['data']:
            loginToken = data['data']['loginToken']
            token = loginToken.get('token')
            user = loginToken.get('user', {})
            openid = user.get('openid')
            unionid = user.get('unionid')
            purePhoneNumber = data['data'].get('purePhoneNumber')
            mobile = data['data'].get('mobile')
            return {
                'success': True,
                'token': token,
                'openid': openid,
                'unionid': unionid,
                'purePhoneNumber': purePhoneNumber,
                'mobile': mobile,
                'raw': data['data'],
                'wxid': wxid
            }
        else:
            return {'success': False, 'error': data.get('message', '未知错误'), 'wxid': wxid}
    except Exception as e:
        return {'success': False, 'error': str(e), 'wxid': wxid}

def get_accounts():
    """从环境变量获取账号信息"""
    accounts = []
    # 从环境变量获取微信ID
    yybpc_wxid_data = os.getenv("yybpc_wxid_data")
    if not yybpc_wxid_data:
        print("❌ 未设置环境变量yybpc_wxid_data，请检查环境变量")
        return accounts

    # 自动检测分隔符
    MULTI_ACCOUNT_SPLIT = ["\n", "@", "&"]
    split_char = None
    for sep in MULTI_ACCOUNT_SPLIT:
        if sep in yybpc_wxid_data:
            split_char = sep
            break
    
    if not split_char:
        # 如果都没有分隔符，默认当作单账号
        wxid_list = [yybpc_wxid_data]
    else:
        wxid_list = yybpc_wxid_data.split(split_char)

    for wxid in wxid_list:
        wxid = wxid.strip()
        if wxid:
            if "=" in wxid:
                wxid = wxid.split("=")[1]
            accounts.append({'wxid': wxid})
    
    return accounts

def main():
    accounts = get_accounts()
    if not accounts:
        print('❌ 未配置账号，请设置环境变量yybpc_wxid_data')
        return
    print(f"\n🎉 共找到 {len(accounts)} 个账号")
    stats = {'total': len(accounts), 'success': 0, 'failed': 0}
    for idx, acc in enumerate(accounts):
        wxid = acc['wxid']
        print(f"\n📌 ━━━━━━ 开始处理 {wxid} ━━━━━━")
        try:
            login_result = get_yybpc_token(wxid)
            if not login_result.get('success'):
                print(f"   ❌ 登录失败: {login_result.get('error')}")
                stats['failed'] += 1
                continue
            token = login_result['token']
            openid = login_result.get('openid')
            unionid = login_result.get('unionid')
            purePhoneNumber = login_result.get('purePhoneNumber')
            mobile = login_result.get('mobile')
            print(f"   ✅ 登录成功: openid:{openid} unionid:{unionid} 手机号:{purePhoneNumber or mobile}")
            print(f"   Qm-User-Token: {token}")
            # 这里可继续添加后续爷爷不泡茶相关API操作，所有请求需带Qm-User-Token
            stats['success'] += 1
        except Exception as e:
            print(f"❌ {wxid} 处理异常: {e}")
            stats['failed'] += 1
        if idx < len(accounts) - 1:
            time.sleep(CONFIG['account_delay'])
    # 统计报告
    report = [
        '✅ 所有账号处理完成',
        f"📊 统计报告:",
        f"├─ 总账号数: {stats['total']}",
        f"├─ 成功: {stats['success']}",
        f"└─ 失败: {stats['failed']}"
    ]
    print('\n' + '\n'.join(report))

if __name__ == '__main__':
    main() 